import 'package:flutter/material.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/article_item.dart';
import 'package:flutter_syt/datas/number_extension.dart';
import 'package:flutter_syt/domain/home/share_api.dart';
import 'package:flutter_syt/domain/news/news_list_page.dart';
import 'package:flutter_syt/domain/news/special_list_page.dart';
import 'package:flutter_syt/domain/widgets/stupid_tabs.dart';
import 'package:flutter_syt/domain/widgets/stupid_title_bar.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/widgets/normal_grid.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';

import 'news_focus_page.dart';

typedef OnScrollerCallback = void Function(double offset);

class NewsPage extends StatefulWidget {
  static Map<String, dynamic> controller = {};
  @override
  State<StatefulWidget> createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController? _tabController;

  List<ArticleTypes> types = [];

  late Future<List<ScrollerTabEntity>> _future;
  List<ScrollerTabEntity> _tabList = [];
  List<Widget> _pageList = [];
  Widget create(String type, int index, element) {
    switch (type) {
      case '1':
        return NewsListPage(index, element);
      case 'special':
        return SpecialListPage(index, element);
      default:
        return SpecialListPage(index, element);
      // throw UnimplementedError("Category type not match");
    }
  }

  loadData() async {
    await queryWeather();
  }

  // Stream<List<ScrollerTabEntity>> loadCategory() async* {
  //   types = await API.shared.article.articleTypes();
  //   yield types
  //       .map((e) => ScrollerTabEntity.create(
  //             e.showType,
  //             e.name,
  //             parseInt(e.showType),
  //             e.alias,
  //           ))
  //       .toList();
  // }

  Future<List<ScrollerTabEntity>> loadCategory(
      {bool isSetsetate = false}) async {
    types = await API.shared.article.articleTypes();
    List<ScrollerTabEntity> entitys = types
        .map((e) => ScrollerTabEntity.create(
              e.showType,
              e.name,
              parseInt(e.showType),
              e.alias,
            ))
        .toList();
//  var list = snapshot.data!;
    // List<ScrollerTabEntity> tabList = [];
    // List<Widget> pageList = [];
    for (int idx = 0; idx < entitys.length; idx++) {
      ScrollerTabEntity element = entitys[idx];
      Widget? page = create(element.type, idx, element);
      _pageList.add(page);
      _tabList.add(element);
    }
    // var temp =
    //     ScrollerTabEntity.create('eye_list', S.of(context).live_2, 1, '');
    // tabList.add(temp);
    // var live = GameLiveSinglePage();
    // live.needBar = false;
    // pageList.add(live);
    if (_tabController == null || _tabController?.length != _tabList.length) {
      _tabController =
          TabController(initialIndex: 0, length: _tabList.length, vsync: this);
    }
    if (isSetsetate) {
      if (mounted) {
        setState(() {});
      }
    }
    return entitys;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _future = loadCategory();
  }

  // if (!snapshot.hasData || snapshot.data == null) {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder<List<ScrollerTabEntity>>(
      future: _future,
      builder: (context, snapshot) {
        // return
        if (!snapshot.hasData || snapshot.data == null) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            child: Center(
              child: ViewStateErrorWidget(
                onPressed: () {
                  // onPressed: () {
                  _future = loadCategory(isSetsetate: true);
                  // },
                },
              ),
            ),
          );
        } else if ((snapshot.data ?? []).isEmpty) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            child: Center(
              // ViewStateEmptyWidget
              child: ViewStateEmptyWidget(),
            ),
          );
        }

        return SafeArea(
          child: Scaffold(
            body: Column(
              children: [
                Container(
                  child: Column(
                    children: [
                      GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onDoubleTap: () {
                            var controller = NewsPage.controller[
                                types[_tabController?.index ?? 0].alias];
                            if (controller is NormalTableViewController) {
                              controller.animateTo(0);
                            } else if (controller is NormalGridController) {
                              controller.animateTo(0);
                            }
                          },
                          child: ColorsTitleBar(
                            weatherEntity,
                            title: S.current.chengdu,
                            isShowWeather: false,
                          )),
                      Container(
                        // margin: EdgeInsets.only(top: 20),
                        child: NormalTabs(
                          _tabList,
                          _tabController!,
                          textColor: Colors.black,
                          // alignment: Alignment.centerLeft,
                        ),
                      ),
                      Container(
                        height: 0.5,
                        color: Colors.black.withOpacity(0.1),
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: TabBarView(
                    controller: _tabController,
                    children: _pageList,
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
    // return StreamBuilder<List<ScrollerTabEntity>>(
    //     initialData: [],
    //     stream: loadCategory(),
    //     builder: (ctx, AsyncSnapshot<List<ScrollerTabEntity>> snapshot) {
    //       if (!snapshot.hasData || snapshot.data == null) {
    //         return Container(
    //           width: double.infinity,
    //           height: double.infinity,
    //           child: Center(
    //             child: ViewStateErrorWidget(),
    //           ),
    //         );
    //       } else if ((snapshot.data ?? []).isEmpty) {
    //         return Container(
    //           width: double.infinity,
    //           height: double.infinity,
    //           child: Center(
    //             // ViewStateEmptyWidget
    //             child: ViewStateEmptyWidget(),
    //           ),
    //         );
    //       }
    //       var list = snapshot.data!;
    //       List<ScrollerTabEntity> tabList = [];
    //       List<Widget> pageList = [];
    //       for (int idx = 0; idx < list.length; idx++) {
    //         ScrollerTabEntity element = list[idx];
    //         Widget? page = create(element.type, idx, element);
    //         pageList.add(page);
    //         tabList.add(element);
    //       }
    //       // var temp =
    //       //     ScrollerTabEntity.create('eye_list', S.of(context).live_2, 1, '');
    //       // tabList.add(temp);
    //       // var live = GameLiveSinglePage();
    //       // live.needBar = false;
    //       // pageList.add(live);
    //       if (_tabController == null ||
    //           _tabController?.length != tabList.length) {
    //         _tabController = TabController(
    //             initialIndex: 0, length: tabList.length, vsync: this);
    //       }
    //       return SafeArea(
    //         child: Scaffold(
    //           body: Column(
    //             children: [
    //               Container(
    //                 child: Column(
    //                   children: [
    //                     GestureDetector(
    //                         behavior: HitTestBehavior.opaque,
    //                         onDoubleTap: () {
    //                           var controller = NewsPage.controller[
    //                               types[_tabController?.index ?? 0].alias];
    //                           if (controller is NormalTableViewController) {
    //                             controller.animateTo(0);
    //                           } else if (controller is NormalGridController) {
    //                             controller.animateTo(0);
    //                           }
    //                         },
    //                         child: ColorsTitleBar(
    //                           weatherEntity,
    //                           title: S.current.chengdu,
    //                           isShowWeather: false,
    //                         )),
    //                     Container(
    //                       // margin: EdgeInsets.only(top: 20),
    //                       child: NormalTabs(
    //                         tabList,
    //                         _tabController!,
    //                         textColor: Colors.black,
    //                         alignment: Alignment.centerLeft,
    //                       ),
    //                     ),
    //                     Container(
    //                       height: 0.5,
    //                       color: Colors.black.withOpacity(0.1),
    //                     )
    //                   ],
    //                 ),
    //               ),
    //               Expanded(
    //                 child: TabBarView(
    //                   controller: _tabController,
    //                   children: pageList,
    //                 ),
    //               )
    //             ],
    //           ),
    //         ),
    //       );
    //     });
  }

  @override
  bool get wantKeepAlive => true;
}

class NewsPageNotChengdu extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _NewsPageNotChengdu();
}

class _NewsPageNotChengdu extends State<NewsPageNotChengdu>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController? _tabController;
  late Future<List<ScrollerTabEntity>> _future;
  List<ScrollerTabEntity> _tabList = [];
  List<Widget> _pageList = [];
  Widget create(String type, int index, ScrollerTabEntity element) {
    var page = NewsFocusPage();
    page.id = element.id ?? '';
    page.showType = element.showType;
    return page;
    // switch (type) {
    //   case 'news':
    //     return NewsFocusPage();
    //   // focus
    //   case 'star':
    //     var page = NewsFocusPage();
    //     page.alias = 'dygs';
    //     return page;
    //   default:
    //     return NewsFocusPage();
    // }
  }

  // Stream<List<ScrollerTabEntity>> loadCategory() async* {
  //   yield [
  //     ScrollerTabEntity.create(
  //       'news',
  //       S().focus_news,
  //       1,
  //       '',
  //     ),
  //     ScrollerTabEntity.create(
  //       'star',
  //       S().universiade_star,
  //       1,
  //       '',
  //     ),
  //   ];
  // }
  // Stream<List<ScrollerTabEntity>> loadCategory() async* {
  //   List<ArticleTypes> types = await API.shared.article.articleIndexTypes();
  //   yield types
  //       .map((e) => ScrollerTabEntity.create(
  //           e.showType, e.title, parseInt(e.showType), e.alias,
  //           id: e.id))
  //       .toList();
  //   // return types;
  // }
  Future<List<ScrollerTabEntity>> loadCategory(
      {bool isSetsetate = false}) async {
    List<ArticleTypes> types = await API.shared.article.articleIndexTypes();
    List<ScrollerTabEntity> entitys = types
        .map((e) => ScrollerTabEntity.create(
            e.showType, e.title, parseInt(e.showType), e.alias,
            id: e.id))
        .toList();

    // var list = snapshot.data!;

    for (int idx = 0; idx < types.length; idx++) {
      ScrollerTabEntity element = entitys[idx];
      Widget? page = create(element.type, idx, element);
      _pageList.add(page);
      _tabList.add(element);
    }
    if (_tabController == null || _tabController?.length != _tabList.length) {
      _tabController =
          TabController(initialIndex: 0, length: _tabList.length, vsync: this);
    }
    if (isSetsetate) {
      if (mounted) {
        setState(() {});
      }
    }
    return entitys;
  }

  @override
  void initState() {
    super.initState();
    _future = loadCategory();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder<List<ScrollerTabEntity>>(
      future: _future,
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data == null) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            child: Center(
              child: ViewStateErrorWidget(
                onPressed: () {
                  _future = loadCategory(isSetsetate: true);
                },
              ),
            ),
          );
        } else if ((snapshot.data ?? []).isEmpty) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            child: Center(
              // ViewStateEmptyWidget
              child: ViewStateEmptyWidget(),
            ),
          );
        }

        return SafeArea(
          child: Scaffold(
            body: Column(
              children: [
                Container(
                  child: Column(
                    children: [
                      GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onDoubleTap: () {
                            try {
                              NewsFocusPage.controller[[
                                'focus',
                                'dygs'
                              ][_tabController?.index ?? 0]]
                                  ?.animateTo(0);
                            } catch (e) {}
                          },
                          child: ColorsTitleBar(
                            weatherEntity,
                            title: S.current.home_news,
                            isShowWeather: false,
                          )),
                      NormalTabs(
                        _tabList,
                        _tabController!,
                        textColor: Colors.black,
                        // alignment: Alignment.centerLeft,
                      ),
                      Container(
                        color: Colors.black.withOpacity(0.1),
                        height: 0.5,
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: TabBarView(
                    controller: _tabController,
                    children: _pageList,
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
    // return StreamBuilder<List<ScrollerTabEntity>>(
    //     initialData: [],
    //     stream: loadCategory(),
    //     builder: (ctx, AsyncSnapshot<List<ScrollerTabEntity>> snapshot) {
    //       if (!snapshot.hasData || snapshot.data == null) {
    //         return Container(
    //           width: double.infinity,
    //           height: double.infinity,
    //           child: Center(
    //             child: ViewStateErrorWidget(),
    //           ),
    //         );
    //       } else if ((snapshot.data ?? []).isEmpty) {
    //         return Container(
    //           width: double.infinity,
    //           height: double.infinity,
    //           child: Center(
    //             // ViewStateEmptyWidget
    //             child: ViewStateEmptyWidget(),
    //           ),
    //         );
    //       }
    //       var list = snapshot.data!;
    //       List<ScrollerTabEntity> tabList = [];
    //       List<Widget> pageList = [];
    //       for (int idx = 0; idx < list.length; idx++) {
    //         ScrollerTabEntity element = list[idx];
    //         Widget? page = create(element.type, idx, element);
    //         pageList.add(page);
    //         tabList.add(element);
    //       }
    //       if (_tabController == null ||
    //           _tabController?.length != tabList.length) {
    //         _tabController = TabController(
    //             initialIndex: 0, length: tabList.length, vsync: this);
    //       }
    //       return SafeArea(
    //         child: Scaffold(
    //           body: Column(
    //             children: [
    //               Container(
    //                 child: Column(
    //                   children: [
    //                     GestureDetector(
    //                         behavior: HitTestBehavior.opaque,
    //                         onDoubleTap: () {
    //                           try {
    //                             NewsFocusPage.controller[[
    //                               'focus',
    //                               'dygs'
    //                             ][_tabController?.index ?? 0]]
    //                                 ?.animateTo(0);
    //                           } catch (e) {}
    //                         },
    //                         child: ColorsTitleBar(
    //                           weatherEntity,
    //                           title: S.current.home_news,
    //                           isShowWeather: false,
    //                         )),
    //                     NormalTabs(
    //                       tabList,
    //                       _tabController!,
    //                       textColor: Colors.black,
    //                       alignment: Alignment.centerLeft,
    //                     ),
    //                     Container(
    //                       color: Colors.black.withOpacity(0.1),
    //                       height: 0.5,
    //                     )
    //                   ],
    //                 ),
    //               ),
    //               Expanded(
    //                 child: TabBarView(
    //                   controller: _tabController,
    //                   children: pageList,
    //                 ),
    //               )
    //             ],
    //           ),
    //         ),
    //       );
    //     });
  }

  @override
  bool get wantKeepAlive => true;
}
